package com.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.SubjectData;
import com.edu.entity.excel.ExcelSubjectData;
import com.edu.entity.subject.OneSubject;
import com.edu.entity.subject.TwoSubject;
import com.edu.listener.ExcelSubjectExcelListener;
import com.edu.mapper.SubjectMapper;
import com.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author mxs
 * @since 2021-10-18
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectData> implements SubjectService {
    /**
     * 读取excel文佳上传到数据库
     *
     * @param file           上传的excel文件
     * @param subjectService
     */
    @Override
    public void importSubjectData(MultipartFile file, SubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(),
                    ExcelSubjectData.class, new ExcelSubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //获取所有一二级分类
        //获取所有一级分类
        QueryWrapper<SubjectData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", "0");
        List<SubjectData> oneSubjectList = baseMapper.selectList(queryWrapper);
        //获取二级分类
        queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("parent_id", "0");
        List<SubjectData> twoSubjectList = baseMapper.selectList(queryWrapper);
        //创建最终列表
        List<OneSubject> finalSubjectList = new ArrayList<>();
        for (SubjectData oneSubjectData : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            //将oneSubjectList中的值逐个取出来赋给oneSubject中，名字要相同
            BeanUtils.copyProperties(oneSubjectData, oneSubject);
            //将二级数据取出并且放到相应子类中
            for (SubjectData twoSubjectData : twoSubjectList) {
                if (twoSubjectData.getParentId().equals(oneSubject.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoSubjectData, twoSubject);
                    //将二级数据添加到一级数据中
                    oneSubject.getChildren().add(twoSubject);
                }
            }
            //将添加了二级数据的一级数据放入最终集合中
            finalSubjectList.add(oneSubject);
        }
        return finalSubjectList;
    }
}
